package com.ks.user.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ks.core.base.OperationContext;
import com.ks.core.constant.Const;
import com.ks.core.dto.SearchCriteriaBase;
import com.ks.core.exception.BizExceptionEnum;
import com.ks.core.exception.GunsException;
import com.ks.core.util.ToolUtil;
import com.ks.user.controller.dto.PowerRoleRequest;
import com.ks.user.controller.dto.RoleRequest;
import com.ks.user.controller.dto.UserRoleRequest;
import com.ks.user.dao.PowerRoleResurceMapper;
import com.ks.user.dao.PowerUserRoleMapper;
import com.ks.user.entity.*;
import com.ks.user.dao.PowerRoleMapper;
import com.ks.user.service.IPowerRoleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ks.user.service._ServiceBase;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author kingdee123
 * @since 2020-11-30
 */
@Service
public class PowerRoleServiceImpl extends _ServiceBase<PowerRoleMapper, PowerRole> implements IPowerRoleService {
    @Resource
    private PowerRoleMapper powerRoleMapper;

    @Resource
    private PowerRoleResurceMapper powerRoleResurceMapper;

    @Resource
    private PowerUserRoleMapper powerUserRoleMapper;


    @Override
    public Map<String, Object> addPowerRole(OperationContext context, PowerRoleRequest powerRoleRequest) {
        PowerRole powerRole = new PowerRole();
        Map<String, Object> result = new HashMap<>();
        powerRole.setIRoleType(powerRoleRequest.getRoleType());
        powerRole.setIRoleName(powerRoleRequest.getRoleName());
        powerRole.setCreateUserID(context.getUserId().intValue());
        if (isSystem(context)) {
            Integer i = powerRoleMapper.insert(powerRole);
            if (i > 0) {
                result.put("data", powerRole);
            } else {
                throw new GunsException("角色添加失败!");
            }
        } else {
            powerRole.setOrgID(context.getOrgId().intValue());
            powerRole.setOrgSubID(context.getOrgSubId().intValue());
            powerRole.setTenantID(context.getTenantId().intValue());
            powerRole.setDataType("TENANT");
            Integer i = powerRoleMapper.insert(powerRole);
            if (i > 0) {
                result.put("data", powerRole);
            } else {
                throw new GunsException("角色添加失败!");
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> updatePowerRole(OperationContext context, PowerRoleRequest powerRoleRequest) {
        PowerRole powerRole = new PowerRole();
        Map<String, Object> result = new HashMap<>();
        powerRole.setIRoleType(powerRoleRequest.getRoleType());
        powerRole.setIRoleName(powerRoleRequest.getRoleName());
        powerRole.setUpdateUserID(context.getUserId().intValue());
        powerRole.setId(powerRoleRequest.getId());
        Integer i = powerRoleMapper.updateById(powerRole);
        if (i > 0) {
            result.put("data", powerRole);
        } else {
            throw new GunsException("角色修改失败!");
        }
        return result;
    }

    @Override
    public Map<String, Object> selectPowerRole(OperationContext context, SearchCriteriaBase searchCriteriaBase) {
        EntityWrapper<PowerRole> wrapper = new EntityWrapper<>();
        PowerRole powerRole = new PowerRole();
        if (isSystem(context)) {
            powerRole.setDataType("SYS");
        } else {
            powerRole.setOrgSubID(context.getOrgSubId().intValue());
            powerRole.setTenantID(context.getTenantId().intValue());
            powerRole.setOrgID(context.getOrgId().intValue());
        }
        powerRole.setDelMark(Const.DEL_FLAG_NORMAL);
        wrapper.setEntity(powerRole);
        RowBounds limit = new Page(searchCriteriaBase.getPageIndex(), searchCriteriaBase.getLimit());
        List<PowerRole> powerRoleList = powerRoleMapper.selectPage(limit, wrapper);
        Map<String, Object> resultMap = this.isResultMap(powerRoleList, searchCriteriaBase);
        return resultMap;
    }

    @Override
    public int deletePowerRole(OperationContext context, PowerRoleRequest powerRoleRequest) {
        EntityWrapper<PowerUserRole> wrapper = new EntityWrapper<>();
        PowerUserRole powerUserRole = new PowerUserRole();
        powerUserRole.setIRoleID(powerRoleRequest.getId());
        powerUserRole.setDelMark(Const.DEL_FLAG_NORMAL);
        wrapper.setEntity(powerUserRole);
        List<PowerUserRole>  powerUserRoles = powerUserRoleMapper.selectList(wrapper);
        if(powerUserRoles.size()>0){
            throw new GunsException("该角色已被引用无法删除!");
        }
        PowerRole powerRole = new PowerRole();
        powerRole.setId(powerRoleRequest.getId());
        if (!isSystem(context)) {
            EntityWrapper<PowerRole> wr = new EntityWrapper<>();
            powerRole.setDataType("SYS");
            wr.setEntity(powerRole);
            List<PowerRole> powerRoles = powerRoleMapper.selectList(wr);
            if(powerRoles.size()>0){
                throw new GunsException("系统角色无法删除!");
            }
        }
        powerRole.setDelMark(Const.DEL_FLAG_DEL);
        Integer i = powerRoleMapper.updateById(powerRole);
        return i;
    }

    @Override
    public int addRole(OperationContext context, RoleRequest roleRequest) {
        int quantity = 0;

        List<Integer> resourceIds = roleRequest.getResurceIds();
        Integer roleid = roleRequest.getRoleId();
        PowerRoleResurce powerRoleResurce = new PowerRoleResurce();

        if (!isSystem(context)) {
            powerRoleResurce.setOrgSubID(context.getOrgSubId().intValue());
            powerRoleResurce.setTenantID(context.getTenantId().intValue());
            powerRoleResurce.setOrgID(context.getOrgId().intValue());
            powerRoleResurce.setDataType("TENANT");
        }


        powerRoleResurce.setIRoleID(roleid);
        for (Integer resourceId : resourceIds) {
            powerRoleResurce.setIResurceID(resourceId);
            PowerRoleResurce newPowerInfo = powerRoleResurceMapper.selectOne(powerRoleResurce);
            if (ToolUtil.isEmpty(newPowerInfo)) {
                powerRoleResurce.setCreateUserID(context.getUserId().intValue());
                Integer i = powerRoleResurceMapper.insert(powerRoleResurce);
                quantity += i;
            } else {
                powerRoleResurce.setUpdateUserID(context.getUserId().intValue());
                newPowerInfo.setDelMark(Const.DEL_FLAG_NORMAL);
                Integer i = powerRoleResurceMapper.updateById(newPowerInfo);
                quantity += i;
            }
        }
        return quantity;
    }

    @Override
    public int setUserRole(OperationContext context, UserRoleRequest userRoleRequest) {
        Integer userId = userRoleRequest.getUserId();
        Integer roleId = userRoleRequest.getRoleId();
        PowerUserRole powerUserRole = new PowerUserRole();

        if (!isSystem(context)) {
            powerUserRole.setOrgSubID(context.getOrgSubId().intValue());
            powerUserRole.setTenantID(context.getTenantId().intValue());
            powerUserRole.setOrgID(context.getOrgId().intValue());
            powerUserRole.setDataType("TENANT");
        }

        powerUserRole.setIUserID(userId);
        powerUserRole.setIRoleID(roleId);

        PowerUserRole newPowerUser = powerUserRoleMapper.selectOne(powerUserRole);
        if (ToolUtil.isEmpty(newPowerUser)) {
            newPowerUser.setCreateUserID(context.getUserId().intValue());
            Integer i = powerUserRoleMapper.insert(newPowerUser);
            return i;
        } else {
            newPowerUser.setUpdateUserID(context.getUserId().intValue());
            newPowerUser.setDelMark(Const.DEL_FLAG_NORMAL);
            Integer i = powerUserRoleMapper.updateById(newPowerUser);
            return i;
        }
    }

    @Override
    public int moveEmpower(OperationContext context, List<Integer> ids, int iRoleId) {
        int count = 0;
        PowerRoleResurce powerRoleResurce = new PowerRoleResurce();
        if (ToolUtil.isNotEmpty(ids)) {
            for (int i = 0; i < ids.size(); i++) {
                powerRoleResurce.setIRoleID(iRoleId);
                powerRoleResurce.setIResurceID(ids.get(i));
                powerRoleResurce.setDelMark(Const.DEL_FLAG_NORMAL);
                PowerRoleResurce roleResurce = powerRoleResurceMapper.selectOne(powerRoleResurce);
                if (ToolUtil.isNotEmpty(roleResurce)) {
                    roleResurce.setDelMark(Const.DEL_FLAG_DEL);
                    Integer integer = powerRoleResurceMapper.updateById(roleResurce);
                    count += integer;
                }
            }
        }
        return count;
    }


    public boolean isSystem(OperationContext context) {
        Long id = context.getTenantId();
        if (id == 0L || id == 0) {
            return true;
        }
        return false;
    }

    public Map<String, Object> isResultMap(List list, SearchCriteriaBase searchCriteriaBase) {
        Map<String, Object> map = new HashMap<>();
        map.put("count", list.size());
        map.put("limit", searchCriteriaBase.getLimit());
        map.put("pageIndex", searchCriteriaBase.getPageIndex());
        map.put("hasMore", false);
        map.put("items", list);
        return map;
    }
}
